package ge.telasi.tasks.report;

import ge.telasi.tasks.EJBLocaleManager;
import ge.telasi.tasks.LocaleManager;
import ge.telasi.tasks.controller.AppConfigController;
import ge.telasi.tasks.model.User;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.persistence.EntityManager;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

/**
 * Base for all report classes.
 * 
 * @author dimitri
 */
public abstract class Report {
    protected static FopFactory fopFactory;

    protected LocaleManager lm = new EJBLocaleManager();
    public abstract String getReport(EntityManager em) throws Exception;

    public byte[] getBytes(EntityManager em) throws Exception {
        // generate report
        String report = getReport(em);

        // create fop factory
        if (fopFactory == null) {
            fopFactory = FopFactory.newInstance();
            try {
                String configPath = new AppConfigController().getAppConfigValue(em, "report.fop_config");
                fopFactory.setUserConfig(new File(configPath));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        // generate byte array
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
        StreamSource src = new StreamSource(new ByteArrayInputStream(report.getBytes("UTF-8")));
        Result res = new SAXResult(fop.getDefaultHandler());
        TransformerFactory.newInstance().newTransformer().transform(src, res);

        return out.toByteArray();
    }

    protected String encode(String text) {
        return text.replace("<", "&lt;").replace(">", "&gt;");
    }

    protected String userToString(User user) {
        StringBuilder b = new StringBuilder();
        b.append(user.getFullName());
        b.append(" <");
        b.append(user.getUsername());
        b.append(">");
        return encode(b.toString());
    }

}
